package com.example.studentdemo.service.impl;

import com.example.studentdemo.constant.RoleConstant;
import com.example.studentdemo.service.AdminService;

import cn.hutool.core.util.StrUtil;
import com.example.studentdemo.entity.Account;
import com.example.studentdemo.entity.Admin;
import com.example.studentdemo.exception.CustomerException;
import com.example.studentdemo.mapper.AdminMapper;
import com.example.studentdemo.utils.PasswordUtils;
import com.example.studentdemo.utils.TokenUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional(rollbackFor = Exception.class)
public class AdminServiceImpl implements AdminService {
    @Resource
    AdminMapper adminMapper;

    @Override
    public List<Admin> selectAll(Admin admin) {
        return adminMapper.selectAll(admin);
    }

    @Override
    public Admin selectByUsername(String username) {
        return adminMapper.selectByUsername(username);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(Admin admin) {
        Admin dbAdmin = adminMapper.selectByUsername(admin.getUsername());
        if (dbAdmin != null) {
            throw new CustomerException("账号重复了");
        }
        if (!StrUtil.isNotBlank(admin.getPassword())) {
            admin.setPassword(PasswordUtils.encryptPassword("admin"));
        }
        admin.setPassword(PasswordUtils.encryptPassword(admin.getPassword()));
        admin.setRole(RoleConstant.ADMIN_ROLE);
        adminMapper.insert(admin);
    }

    @Override
    public void update(Admin admin) {
        adminMapper.updateById(admin);
    }

    @Override
    public PageInfo<Admin> selectPage(Integer pageNum, Integer pageSize, Admin admin) {
        // 开启分页查询
        PageHelper.startPage(pageNum, pageSize);
        List<Admin> adminList = adminMapper.selectAll(admin);
        return PageInfo.of(adminList);
    }

    @Override
    public void deleteById(Integer id) {
        adminMapper.deleteById(id);
    }


    @Override
    public void deleteBatch(List<Admin> adminList) {
        for (Admin admin : adminList) {
            this.deleteById(admin.getId());
        }
    }

    @Override
    public Admin selectById(Integer userId) {
        return adminMapper.selectById(userId);
    }

    @Override
    public Admin login(Account account) {
        // 验证账号是否存在
        Admin dbAdmin = adminMapper.selectByUsername(account.getUsername());
        if (dbAdmin == null) {
            throw new CustomerException("账号不存在");
        }
        // 验证密码是否正确
        if (!PasswordUtils.matchesPassword(account.getPassword(), dbAdmin.getPassword())) {
            throw new CustomerException("账号或密码错误");
        }
        // 获取设备ID（从account中获取或生成默认值）
        String deviceId = account.getDeviceId();
        if (StrUtil.isBlank(deviceId)) {
            deviceId = "default-device";
        }
        // 使用TokenUtils生成令牌
        String token = TokenUtils.createToken(String.valueOf(dbAdmin.getId()), "ADMIN", dbAdmin.getPassword(), deviceId);
        dbAdmin.setToken(token);
        return dbAdmin;
    }

    @Override
    public void updatePassword(Account account) {
        Account currentUser = TokenUtils.getCurrentUser();
        if (currentUser != null) {
            if (!PasswordUtils.matchesPassword(account.getPassword(), currentUser.getPassword())) {
                throw new CustomerException("500", "原密码输入错误");
            }
            Admin dbAdmin = adminMapper.selectById(currentUser.getId());
            // 密码更新后，注销该用户的所有登录会话
            TokenUtils.logoutAll(String.valueOf(dbAdmin.getId()), "ADMIN");
            dbAdmin.setPassword(PasswordUtils.encryptPassword(account.getNewPassword()));
            adminMapper.updateById(dbAdmin);
        }
    }
}
